const MinminToken = artifacts.require('MinminToken.sol')
const Exchange = artifacts.require('Exchange.sol')

module.exports = async function(callback) {
  const minminToken = await MinminToken.deployed()
  const exchange = await Exchange.deployed()
  const accounts = await web3.eth.getAccounts()
  const ETHER_ADDRESS = '0x0000000000000000000000000000000000000000'

  try {
    console.log('======= init account =======');
    await ylog(accounts[0], 'eth', ETHER_ADDRESS)  
    await ylog(accounts[0], 'min', minminToken.address) 
    await ylog(accounts[1], 'eth', ETHER_ADDRESS)  
    await ylog(accounts[1], 'min', minminToken.address) 
  
    console.log('=========== deposit ==========');
    // 存入 ETH 币
    await exchange.depositEther({
      from: accounts[0],
      value: toWei(10)
    })
    await exchange.depositEther({
      from: accounts[1],
      value: toWei(10)
    })
    // 存入 min 币
    await minminToken.approve(exchange.address, toWei(1000), {
      from: accounts[0]
    })
    await exchange.depositToken(minminToken.address, toWei(1000), {
      from: accounts[0]
    })
  
  
    await ylog(accounts[0], 'eth', ETHER_ADDRESS)  
    await ylog(accounts[0], 'min', minminToken.address) 
    await ylog(accounts[1], 'eth', ETHER_ADDRESS)  
    await ylog(accounts[1], 'min', minminToken.address) 
  
    console.log('=========== order ==========');
    // 创建订单
    let res; 
    let order;
    res = await exchange.makeOrder(ETHER_ADDRESS, toWei(5), minminToken.address, toWei(1), {
      from: accounts[0]
    })
    order = res.logs[0].args
    // console.log(order)
    console.log('=========== cancel ==========');
    await exchange.cancelOrder(order.id, {
      from: accounts[0]
    })
    console.log('=========== fill ==========');
    res = await exchange.makeOrder(ETHER_ADDRESS, toWei(5), minminToken.address, toWei(1), {
      from: accounts[0]
    })
    order = res.logs[0].args
  
    // await exchange.fillOrder(order.id, {
    //   from: accounts[1]
    // })
    await ylog(accounts[0], 'eth', ETHER_ADDRESS)  
    await ylog(accounts[0], 'min', minminToken.address) 
    await ylog(accounts[1], 'eth', ETHER_ADDRESS)  
    await ylog(accounts[1], 'min', minminToken.address) 
  } catch (error) {
    console.log(error)
  }

  console.log('=========== end ==========');
  async function ylog(account, token, address) {
    const res = await exchange.tokens(address, account)
    console.log(`${account} - ${token} - ${fromWei(res)}`);
  }
  callback()
}

function fromWei(val) {
  return web3.utils.fromWei(val, 'ether')
}

function toWei(val) {
  return web3.utils.toWei(val.toString(), 'ether')
}
